package com.pingan.glue.gluegame.controller;

import com.pingan.glue.gluegame.common.ErrorMessage;
import com.pingan.glue.gluegame.controller.form.FriendRegisterForm;
import com.pingan.glue.gluegame.controller.form.LoginResponse;
import com.pingan.glue.gluegame.entity.FaceFieldEntity;
import com.pingan.glue.gluegame.entity.FriendUserEntity;
import com.pingan.glue.gluegame.response.ResponseData;
import com.pingan.glue.gluegame.service.FaceService;
import com.pingan.glue.gluegame.service.FriendUserService;
import com.pingan.glue.gluegame.service.FriendUserTokenService;
import com.pingan.glue.gluegame.service.SysCaptchaService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

@Controller
@RequestMapping("register")
public class FriendUserRegisterController {

    private final static Logger LOGGER = LoggerFactory.getLogger(FriendUserRegisterController.class);

    @Resource
    private SysCaptchaService sysCaptchaService;
    @Resource
    private FriendUserService friendUserService;
    @Resource
    private FriendUserTokenService friendUserTokenService;
    @Resource
    private FaceService faceService;

    @PostMapping
    private @ResponseBody
    ResponseData<LoginResponse> register(@RequestBody FriendRegisterForm form){
        LOGGER.info("FriendUserLoginController_register_params={}",form);

        if (StringUtils.isBlank(form.getCode())||StringUtils.isBlank(form.getMobile())) {
            return ResponseData.error(ErrorMessage.MOBILE_CODE_NOT_NULL);
        }

       /* boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if(!captcha){
            return ResponseData.error(ErrorMessage.CAPTCHA);
        }*/

        //用户信息
        FriendUserEntity user = friendUserService.queryByMobile(form.getMobile());

        if(user != null) {
            return ResponseData.error(ErrorMessage.USERNAME_EXIST);
        }
        user = new FriendUserEntity();
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        user.setMobile(form.getMobile());
        user.setStatus(1);
        Integer i = friendUserService.createUser(user);

        //生成token，登陆
        String token = friendUserTokenService.createToken(user.getUserId());
        FaceFieldEntity face= faceService.queryFaceFromDb(user.getUserId());
        LoginResponse lr = new LoginResponse();
        lr.setToken(token);
        lr.setHaveImages(face != null);
        return ResponseData.success(lr);
    }
}
